package com.framework.service.personalCenter.impl;

import com.framework.common.exception.login.LoginFailLimitException;
import com.framework.common.model.response.R;
import com.framework.common.util.encrypt.MD5Util;
import com.framework.common.util.encrypt.PasswordUtil;
import com.framework.common.util.encrypt.RSAEncrypt;
import com.framework.common.util.other.NumeralUtil;
import com.framework.mapper.system.SystemUserMapper;
import com.framework.model.system.vo.SystemUserVo;
import com.framework.service.base.BaseService;
import com.framework.service.personalCenter.PersonalCenterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.data.redis.RedisIndexedSessionRepository;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;

/**
 * @author 龘鵺
 * @version 1.0
 * @className com.framework.service.personalCenter.impl
 * @description 帐号登录个人中心业务接口实现类
 * @datetime 2020-01-09 11:11:11
 */
@Service("personalCenterServiceImpl")
public class PersonalCenterServiceImpl extends BaseService implements PersonalCenterService {
    private Logger log = LoggerFactory.getLogger(PersonalCenterServiceImpl.class);
    //    @Autowired
//    private SystemUserService systemUserServiceImpl;
    @Autowired
    private SystemUserMapper systemUserMapper;
    @Autowired
    private FindByIndexNameSessionRepository<? extends Session> sessionRepository;
    @Autowired
    private RedisIndexedSessionRepository redisIndexedSessionRepository;

    /**
     * @return com.framework.model.system.vo.SystemUserVo
     * @title 获取当前登录帐号信息
     * @description 获取当前登录帐号信息
     * @author 龘鵺
     * @datetime 2020-01-09 11:11:11
     */
    @Override
    public SystemUserVo getLoginNameUser() {
        SystemUserVo systemUserVo = systemUserMapper.selectByPrimaryKey(getUserId());
        return systemUserVo;
    }

    /**
     * @return com.framework.common.model.response.R
     * @title 获取当前登录帐号信息
     * @description 获取当前登录帐号信息
     * @author 龘鵺
     * @datetime 2025-01-09 11:11:11
     */
    @Override
    public R<?> getLoginUser() {
        return R.ok(getLoginNameUser());
    }

    /**
     * @param oldPassword     1 旧密码
     * @param password        2 新密码
     * @param confirmPassword 3 确认密码
     * @return com.framework.common.model.response.R
     * @title 帐号个人密码修改
     * @description 帐号个人密码修改
     * @author 龘鵺
     * @datetime 2020-01-09 11:11:11
     */
    @Override
    public R<?> edit(String oldPassword, String password, String confirmPassword) {
        SystemUserVo su = getUser();
        try {
            oldPassword = RSAEncrypt.decryptPrivate(oldPassword, PasswordUtil.privateKey);
            password = RSAEncrypt.decryptPrivate(password, PasswordUtil.privateKey);
            confirmPassword = RSAEncrypt.decryptPrivate(confirmPassword, PasswordUtil.privateKey);
        } catch (Exception e) {
            log.error("save:解密错误:{}", su.getAccount());
            throw new LoginFailLimitException("解密错误！");
        }
        String oldPW = MD5Util.MD5EncodeToPassword(oldPassword, su.getSalt());
        if (!su.getPassword().equals(oldPW)) {
            return R.fail("旧密码错误!");
        }
        String newPW = MD5Util.MD5EncodeToPassword(password, su.getSalt());
        if (newPW.equals(oldPW)) {
            return R.fail("新旧密码不相同!");
        }
        if (!password.equals(confirmPassword)) {
            return R.fail("确认密码不相同!");
        }
        if (password.length() < NumeralUtil.POSITIVE_SIX || password.length() > NumeralUtil.POSITIVE_TWENTY_FIVE) {
            return R.fail("密码最少6至最多25个字符！");
        }
        SystemUserVo param = new SystemUserVo();
        param.setPassword(newPW);
        param.setId(getUserId());
        systemUserMapper.updateByPrimaryKeySelective(param);
        // 查询帐号的 Session 信息，返回值 key 为 sessionId
        Map<String, ? extends Session> userSessions = sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, su.getAccount());
        if (userSessions.size() > NumeralUtil.POSITIVE_ZERO) {
            // 移除帐号的 session 信息
            Set<String> sessionIds = userSessions.keySet();
            if (sessionIds.size() > NumeralUtil.POSITIVE_ZERO) {
                for (String session : sessionIds) {
                    redisIndexedSessionRepository.deleteById(session);
                }
            }
        }
        return R.ok( "修改成功,请重新登录!");
    }

    /**
     * @param row 1 帐号信息实体类对象
     * @return com.framework.common.model.response.R
     * @title 帐号个人信息修改
     * @description 帐号个人信息修改
     * @author 龘鵺
     * @datetime 2020-01-09 11:11:11
     */
    @Override
    public R<?> edit(SystemUserVo row) {
        SystemUserVo param = new SystemUserVo();
        param.setName(row.getName());
        param.setEmail(row.getEmail());
        param.setPhone(row.getPhone());
        param.setId(getUserId());
        systemUserMapper.updateByPrimaryKeySelective(param);
        return R.ok();
    }
}
